"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : dolphin插件
Case Name   : 先连接到加载了插件的B类型数据库，再切到A数据库，再回切到加载了
              插件的B类型数据库
Create At   : 2022.04.12
Owner       : z@wan005
Description :
    1.创建b库
    2.其中一个b库下创建插件
    3.兼容b库且有插件下创建测试用户和表
    4.兼容b库且有插件下给表插入大量数据
    5.切换到兼容A库建表
    6.切回b库且有插件执行删除表数据
    7.修改线程池参数为on
    8.兼容b库且有插件给表插入大量数据
    9.切换到A类型库建表
    10.切回b库且有插件执行删除表数据
    11.清理环境
Expect      :
     1.成功
     2.成功
     3.成功
     4.成功
     5.合理报错
     6.成功
     7.成功
     8.成功
     9.合理报错
     10.删除成功
     11.清理环境完成
History     :modified by z@wan005,2022.08.29，om数据库目前实现自动加载dolphin插件，
             因此删除用例中拷贝插件依赖文件步骤
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class PluginTest023(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.com = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.us_name = "us_plugin0023"
        self.tb_name = "tb_plugin0023"
        self.db_name = "db_plugin0023"
        self.default_value = self.com.show_param('enable_thread_pool')
        sql_res = self.pri_sh.execut_db_sql('alter system set '
                                            'enable_thread_pool to off;')
        self.log.info(sql_res)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.log.info(restart_msg)

    def test_dolphin(self):
        text = '----step1:创建b库;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} DBCOMPATIBILITY ='b';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)

        text = '--step2:连接b库查询插件是否存在;expect:插件自动加载---'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(sql_res)
        self.assertEqual('dolphin', sql_res.splitlines()[-2].strip(),
                         '执行失败' + text)

        text = '--step3:兼容b库且有插件下创建测试用户和表;expect:成功-----'
        self.log.info(text)
        cmd = f'''drop user if exists {self.us_name};\
        create user {self.us_name} with sysadmin  password \
        '{macro.PASSWD_INITIAL}';     
        drop table if  exists {self.tb_name};\
        create table {self.tb_name} \
        (id int, name text(10));'''
        result = self.pri_sh.execut_db_sql(cmd, dbname=self.db_name)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result,
                      '执行失败' + text)

        text = '---step4:兼容b库且有插件下给表插入大量数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f'''insert into {self.tb_name} values \
        (generate_series(1,1000000), 'col'|| generate_series(1,1000000));'''
        res = self.pri_sh.execut_db_sql(sql=sql_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res,
                      '执行失败' + text)

        text = '---step5:切换到兼容A库建表;expect:合理报错-----'
        self.log.info(text)
        create_cmd = f'''drop table if  exists {self.tb_name};\
        create table {self.tb_name} (id int, name text(10), salary double);'''
        res = self.pri_sh.execut_db_sql(sql=create_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname='postgres')
        self.log.info(res)
        self.assertIn('ERROR', res, '执行失败' + text)

        text = '---step6:切回b库且有插件执行删除表数据;expect:成功-----'
        self.log.info(text)
        delete_cmd = f'''delete {self.tb_name};'''
        res = self.pri_sh.execut_db_sql(sql=delete_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, res,
                      '执行失败' + text)

        text = '---step7:修改线程池参数为on;expect:成功-----'
        self.log.info(text)
        cmd = f'alter system set enable_thread_pool to on;'
        result = self.pri_sh.execut_db_sql(cmd)
        self.log.info(result)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.log.info(restart_msg)

        text = '---step8:兼容b库且有插件给表插入大量数据;expect:成功-----'
        self.log.info(text)
        insert_cmd = f'''insert into {self.tb_name} values \
               (generate_series(1,1000000), 'col'|| \
               generate_series(1,1000000));'''
        res = self.pri_sh.execut_db_sql(sql=insert_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res,
                      '执行失败' + text)

        text = '---step9:切换到A库建表;expect:合理报错-----'
        self.log.info(text)
        create_cmd = f'''drop table if  exists {self.tb_name};\
               create table {self.tb_name} (id int, name text(10));'''
        res = self.pri_sh.execut_db_sql(sql=create_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname='postgres')
        self.log.info(res)
        self.assertIn('ERROR', res, '执行失败' + text)

        text = '---step10:切回b库且有插件执行删除表数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f'''delete {self.tb_name};'''
        res = self.pri_sh.execut_db_sql(sql=sql_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, res,
                      '执行失败' + text)

    def tearDown(self):
        text = '---step11:清理环境; expect:清理环境成功-----'
        self.log.info(text)
        self.log.info('删除数据库')
        cmd = f"drop database if exists {self.db_name};" \
              f"drop user if exists {self.us_name};"
        result = self.pri_sh.execut_db_sql(cmd)
        self.log.info(result)
        self.log.info('恢复参数默认值')
        self.pri_sh.execute_gsguc(
            "set", self.constant.GSGUC_SUCCESS_MSG,
            f"enable_thread_pool = {self.default_value}")
        self.pri_sh.restart_db_cluster()
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
